<?php

namespace app\api\controller;

use addons\shopro\library\notify\channel\WxOfficeAccount;
use addons\shopro\library\Wechat;
use app\admin\model\UserRule;
use app\common\controller\Base;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\Clock;
use app\common\model\CommissionLog;
use app\common\model\ExpenseRecords;
use app\common\model\UserGroup;
use app\common\model\UserOauth;
use app\common\model\UserTitle;
use fast\Random;
use think\Config;
use think\Validate;

/**
 * 会员接口
 */
class User extends Base
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'bind','register', 'resetpwd', 'changeemail', 'changemobile', 'third','getOpenid'];
    protected $noNeedRight = ['index','changePwd','commission','clock','clock_log','expense','expense_records','bind','getOpenid','rules'];

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 获取Openid
     */
    public function getOpenid()
    {
        repeat_filter();        // 防抖
        $code = $this->request->post('code');
        if (!$code){
            $this->error(__('Invalid parameters'));
        }
        $wechat = new \app\common\library\Wechat('wxOfficialAccount');
        $oauth = $wechat->oauth();
        $decryptSession = $oauth->user()->getOriginal();
        if (!isset($decryptSession['openid'])) {
            $this->error('未获取openid,请重启应用');
        }
        $this->success('ok', $decryptSession);
    }

    /*
     * 获取公众号的openid
     */
    public function getWxOfficialAccountOpenid($code)
    {
        $appid = get_addon_config('dep')['wxOfficialAccount']['app_id'];
        $secret = get_addon_config('dep')['wxOfficialAccount']['secret'];
        // 构造向微信服务器请求的URL
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$secret}&code={$code}&grant_type=authorization_code";

        // 初始化curl
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 发送请求并获取响应
        $response = curl_exec($ch);
        curl_close($ch);

        // 解析微信服务器返回的JSON数据
        $result = json_decode($response, true);
        if (isset($result['openid'])) {
            return $result['openid'];
        } else {
            $this->error('获取openid失败，错误信息：'.$response);
        }
    }


    /*
     * 绑定openid
     */
    public function bind()
    {
        repeat_filter();        // 防抖
        $account = $this->request->post('account');
        $code = $this->request->post('code');
        if (!$account || !$code){
            $this->error(__('Invalid parameters'));
        }
        //获取账号信息
        $field = Validate::is($account, 'email') ? 'email' : (Validate::regex($account, '/^1\d{10}$/') ? 'mobile' : 'username');
        $user = \app\common\model\User::get([$field => $account]);
        if (!$user) {
            $this->error(__('Account is incorrect'));
        }
        if ($user->status != 'normal') {
            $this->error(__('Account is locked'));
        }
        //删除用户之前的绑定信息
        UserOauth::where('user_id',$user->id)->delete();
        $openid = $this->getwxOfficialAccountOpenid($code);
        //绑定第三方授权信息
        $oauth = UserOauth::create([
            'user_id'           => $user->id,
            'openid'            => $openid,
            'platform'          => 'wxOfficialAccount',
        ]);
        $this->success('操作成功',$oauth);
    }


    /**
     * 会员中心
     */
    public function index()
    {
        $data['userinfo'] = $this->auth->getUserinfo();
        $data['clock'] = Clock::getUserDay();
        $data['about'] = [
            'name' => \config('site.name'),
            'version'  => \config('site.version')
        ];
        $this->success('个人中心', $data);
    }


    /*
     * 工作台权限
     */
    public function rules()
    {
        $data = UserRule::getMenuRules();
        $my = $this->auth->getRuleList();
        foreach ($data as $key=>&$item) {
            if (!$item->childs){
                continue;
            }
            foreach ($item->childs as $child) {
                $child['selected'] = false;
                foreach ($my as $v) {
                    if ($child['id'] == $v['id']) {
                        $child['selected'] = true;
                        break;
                    }
                }
            }
        }
        $this->success('权限', $data);
    }


    /*
     * 打卡
     */
    public function clock()
    {
        $params = $this->request->post();
        $params['type'] = isMorningAfternoon();
        $this->apiValidate($params, \app\api\validate\Clock::class,'clock');
        $this->success('打卡成功',Clock::onClock($params));
    }


    /*
     * 打卡记录
     */
    public function clock_log()
    {
        $params = $this->request->get();
        $data = Clock::getClockLogs($params);
        $this->success('打卡记录',$data);
    }

    /*
     * 编辑开支记录
     */
    public function expense()
    {
        $params = $this->request->post();
        $this->apiValidate($params, \app\api\validate\Expense::class,'edit');
        $this->success('操作成功',ExpenseRecords::expenseEdit($params));
    }

    /*
     * 开支记录查询
     */
    public function expense_records()
    {
        $params = $this->request->get();
        $this->success('开支记录',ExpenseRecords::getLists($params));
    }


    /*
     * 提成查询
     */
    public function commission()
    {
        $params = $this->request->get();
        $this->success('提成记录',CommissionLog::getLists($params));
    }

    /**
     * 岗位职称
     */
    public function titles()
    {
        $this->success('岗位职称',UserTitle::getList());
    }


    /**
     * 员工列表
     */
    public function lists()
    {
        $params = $this->request->get();
        $data = \app\common\model\User::getAccountLists($params);
        $this->success('员工列表',$data);
    }

    /**
     * 员工编辑
     */
    public function edit()
    {
        $id = '';
        $remark = '';
        $params = $this->request->post();
        $this->apiValidate($params,\app\api\validate\User::class,'edit');
        extract($params);
        //判断岗位
        $title = UserTitle::get($title_id);
        if (!$title){
            $this->error('岗位职称不存在');
        }
        //判断角色
        $group_num = UserGroup::whereIn('id',$group_ids)->count();
        if (count($group_ids) != $group_num){
            $this->error('角色失效，请重新选择');
        }
//        dp('岗位和角色验证通过');
        //如果id不存在执行添加用户操作
        if (!isset($id) || !$id){
            if (!$password){
                $this->error('密码不能为空');
            }
            $extend['nickname'] = $nickname;
            $extend['id_card'] = $id_card;
            $extend['title_id'] = $title_id;
            $extend['group_ids'] = join(',',$group_ids);
            $extend['remark'] = $remark;
            $extend['UID'] = rand_numer(8);
            $username = $extend['UID'];
            $ret = $this->auth->register($username, $password, '', $mobile, $extend);
            if ($ret){
                $this->success('添加成功',$ret);
            }else{
                $this->error($this->auth->getError());
            }
        }else{
            if ($id == 1){
                $this->error('默认超级管理员不可编辑或删除');
            }
            //执行编辑用户信息
            $row = \app\common\model\User::get($id);
            if (!$row){
                $this->error('用户不存在');
            }
            $row->validate('edit'); //数据验证
            $salt =  Random::alnum();
            $data['nickname'] = $nickname;
            $data['mobile'] = $mobile;
            $data['id_card'] = $id_card;
            $data['title_id'] = $title_id;
            $data['group_ids'] = join(',',$group_ids);
            $data['remark'] = $remark;
            if ($password != ''){
                $data['salt'] = $salt;
                $data['password'] = \app\common\library\Auth::instance()->getEncryptPassword($password, $salt);
            }
            $ret = \app\common\model\User::where('id',$id)->update($data);
        }
        $this->success('操作成功',$ret);
    }

    /**
     * 员工删除
     */
    public function del()
    {
        $id = $this->request->post('id');
        if (!$id) {
            $this->error(__('Invalid parameters'));
        }
        $row = \app\common\model\User::get($id);
        if (!$row){
            $this->error('员工不存在');
        }
        $this->success('员工已删除',$row->delete());
    }


    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="account", type="string", required=true, description="账号")
     * @ApiParams (name="password", type="string", required=true, description="密码")
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @ApiParams (name="avatar", type="string", required=true, description="头像地址")
     * @ApiParams (name="username", type="string", required=true, description="用户名")
     * @ApiParams (name="nickname", type="string", required=true, description="昵称")
     * @ApiParams (name="bio", type="string", required=true, description="个人简介")
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改密码
     *
     * @param string $oldpassword 旧密码
     * @param string $newpassword 新密码
     */
    public function changePwd()
    {
        $user = $this->auth->getUser();

        $oldpassword = $this->request->post("oldpassword");
        $newpassword = $this->request->post("newpassword");

        if (!$newpassword || !$oldpassword) {
            $this->error(__('Invalid parameters'));
        }
        if (strlen($newpassword) < 6 || strlen($newpassword) > 16) {
            $this->error(__('密码长度 6-16 位')); //TODO:密码规则校验
        }

        $ret = $this->auth->changepwd($newpassword, $oldpassword);

        if ($ret) {
            $this->auth->direct($user->id);
            $data = ['userinfo' => $this->auth->getUserinfo()];

            $this->success(__('Change password successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @ApiParams (name="email", type="string", required=true, description="邮箱")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="platform", type="string", required=true, description="平台名称")
     * @ApiParams (name="code", type="string", required=true, description="Code码")
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="newpassword", type="string", required=true, description="新密码")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
}
